﻿var musics =
[
    "A Horse With No Name.mp3",
    "All Souls Waltz.mp3",
    "Brother Budd.mp3",
    "Catch and Release.mp3",
    "Elite C-2 Leadership Development Course Trailer.mp4",
    "Hotel California.mp3",
    "Love Will Keep Us Alive.mp3",
    "Music Box.mp3",
    "Obama Inaugural Speech.mp3",
    "Run Away with Me.mp3",
    "Sitting on Top of the Mountain.mp3",
    "Stars and Stripes Forever.mp3",
    "Time of Our Lives.mp3",
    "Wayfaring Stranger.mp3",
    "What Makes You Beautiful.mp3",
    "Windows开机.mp3",
    "With an Orchid.mp3",
    "With or Without You.mp3",
    "不装饰你的梦.mp3",
    "平凡之路.mp3",
    "故乡山川.mp3",
    "天使与海豚.mp3"
]
;

function randomMusic() {
	var index = parseInt(Math.random() * musics.length);
	var name = musics[index];
//	name = "天使与海豚.mp3";
	console.log(musics,index,name);
	$("audio").attr("title", name);
	var musicurl = "https://gitee.com/thewire/bible/raw/master/songs/" + name;
	
	return musicurl;
}

var repo = "https://gitee.com/thewire/todos/raw/master/high/";

function loadDirectory() {
		var name = "C103Happy2018.xlsx";
		var aceurl = repo + name;
		if (confirm("点击 [确定] 下载通讯录 " + name)) {
				window.open(aceurl);
		}
}

var isWindows = /windows|win32/i.test(navigator.userAgent);

function fish() {
		$(document.body).mousedown(function(){
				checkCtrl(event);
		});
		
		var cities = '<select id="cities" class="form-control input-sm" style="high:30;width:auto;display:inline"></select></li>';
		var criteria = '<input id="criteria" type="text" class="form-control input-sm" style="width:245px;display:inline">';
		var kount = '<label id="kount" class="label label-success" style="width:100%;display:inline" />';

		$("#panel").prepend('<audio controls autoplayx="autoplay" loop="true"><source id="bgmusic" type="audio/mp3">');
		$("#myList").prepend(criteria + '&nbsp;' + kount);
		$("#criteria")[0].focus();
		$("#criteria").attr("placeholder", "输入关键字，按回车搜索");
    $("#bgmusic").attr("src", randomMusic());
    
    var arrAce = [
    	["load","default","通讯录","下载获取通讯录文件"],
    	["pick","primary","查坐标","进入查询坐标页面"],
    	["clear","success","清除","清除信息提示"],
    	["capture","info","截屏","截取当前屏幕，同时按Ctrl将隐藏当前窗口"],
    	["switch","primary",">>","显示/隐藏右边的面板"]
    ];

		$("<li></li>").append(cities).appendTo("#btnList");
    for(var k = 0; k < arrAce.length; k++) {
    	var item = arrAce[k];
    	console.log(item[0] == "capture", isWindows);
    	if(item[0] == "capture" && !isWindows) {
    			continue;
    	}
			var line = '<span style="cursor:default" id="' + item[0] + '" class="label label-' + item[1] + '" title="' + item[3] + '">' + item[2] + '</span>';   	
    	$("<li></li>").append(line).appendTo("#btnList"); 
    }
    
    $("#clear").click(function(){
    		markerList.clearSelected();
    });
    $("#pick").click(function(){
    		window.open("picker.html")
    });
    $("#load").click(function(){
    		loadDirectory();
    });
    $("#capture").click(function(){
    		StartCapture();
    });
    $("#pick").click(function(){
    	window.open("picker.html")
    });
    $("#switch").click(function(){    		
    	   $("#panel").toggle();
    	  var isHidden = $("#panel").is(":hidden");
    	  var panelWidth = isHidden ? 0 : 300;
    	  var switchTxt = isHidden ? "<<" : ">>";
    	  $("#outer-box").css("padding-right", panelWidth);
    	  $("#btnList").css("right", panelWidth);
    	  $("#switch").text(switchTxt);
				if(isHidden) {
    	  		map.zoomIn();
    	  } else {
    	  		map.zoomOut();
    	  }
    		setTimeout(function () { map.setFitView(); }, 500); 
    });
    
    //switch
    $("#kount").attr("title","随机切换背景音乐");
    $("#kount").click(function(){
    	$("#bgmusic").attr("src", randomMusic());
    	$("audio")[0].load();
//    	$("audio")[0].play();
    });
    
    $("title").html("青春103地图 by Carospop");
		
    //创建地图
    var map = new AMap.Map('container', {
        zoom: 7
    });
    
    map.plugin(["AMap.ToolBar"],function(){
        //加载工具条
        tool = new AMap.ToolBar();
        map.addControl(tool);
    });

    AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
        function(MarkerList, SimpleMarker, SimpleInfoWindow) {

            //即jQuery/Zepto
            var $ = MarkerList.utils.$;

            var defaultIconStyle = 'red', //默认的图标样式
                hoverIconStyle = 'green', //鼠标hover时的样式
                selectedIconStyle = 'purple' //选中时的图标样式
            ;

            var markerList = new MarkerList({
                map: map,
                //ListElement对应的父节点或者ID
                listContainer: "myList", //document.getElementById("myList"),
                //选中后显示

                //从数据中读取位置, 返回lngLat
                getPosition: function(item) {
                    //return [item.longitude, item.latitude];
                    return item.location.split(',');
                },
                //数据ID，如果不提供，默认使用数组索引，即index
                getDataId: function(item, index) {

                    return item.name;
                },
                getInfoWindow: function(data, context, recycledInfoWindow) {
                		var href = "https://www.baidu.com/s?wd=" + encodeURI(data.name);
										var link = '<a target="_blank" href="' + href + '\">' + data.name + '</a>';
                    if (recycledInfoWindow) {
                        recycledInfoWindow.setInfoTitle(link);
                        recycledInfoWindow.setInfoBody(data.address);

                        return recycledInfoWindow;
                    }

                    return new SimpleInfoWindow({
                        infoTitle: link,
                        infoBody: data.address,
                        offset: new AMap.Pixel(0, -37)
                    });
                },
                //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
                getMarker: function(data, context, recycledMarker) {

                    //var label = String.fromCharCode('A'.charCodeAt(0) + context.index) + data.name;
                    var label = "&nbsp;" + (context.index + 1) + data.name;
                    if (recycledMarker) {
                        recycledMarker.setIconLabel(label);
                        return;
                    }

                    return new SimpleMarker({
                        containerClassNames: 'my-marker',
                        iconStyle: defaultIconStyle,
                        iconLabel: label
                    });
                },
                //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
                getListElement: function(data, context, recycledListElement) {

                    //var label = String.fromCharCode('A'.charCodeAt(0) + context.index);
										var label = context.index + 1;
                    //使用模板创建
                    var lines = [];
                    lines.push('<div class="poi-imgbox">');
                    lines.push('<span class="poi-img" style="background-image:url(' + repo + 'images/<%- data.phone %>.jpg)"></span>');
                    lines.push('</div>');
                    lines.push('<div class="poi-info-left">');
                    lines.push('    <div class="poi-info">');
                    lines.push('        <font color="green"><%- label %>. <%- data.name %></font> <font color="blue"><%- data.phone %></font>');
                    lines.push('    </div>');
                    lines.push('    <h3 class="poi-title">');
                    lines.push('        <p class="poi-addr"><font color="blue"><%- data.city %></font> <%- data.address %></p>');
                    lines.push('    </h3>');
                    lines.push('</div>');
                    //lines.push('<div class="clear"></div>');
                    var divs = lines.join('');
                    var innerHTML = MarkerList.utils.template(divs, {
                            data: data,
                            label: label
                        });

                    if (recycledListElement) {
                        recycledListElement.innerHTML = innerHTML;
                        return recycledListElement;
                    }

                    return '<li class="poibox">' + innerHTML + '</li>';
                },
                //列表节点上监听的事件 listElementEvents: ['click', 'mouseenter', 'mouseleave'],
                listElementEvents: ['click', 'mouseleave'],
                //marker上监听的事件 markerEvents: ['click', 'mouseover', 'mouseout'],
                markerEvents: ['click', 'mouseover', 'mouseout'],
                //makeSelectedEvents:false,
                selectedClassNames: 'selected',
                autoSetFitView: true
            });

						var toSearchTimer = null;
						$("#criteria").bind("input", function(){
								if(toSearchTimer) {
										clearTimeout(toSearchTimer);
								}
								toSearchTimer = setTimeout(function(){
										var myCriteria = $.trim($("#criteria").val());
										loadData(myCriteria);
								}, 800);
						});
						
						$("#criteria").keyup(queryViaEnter);
						function queryViaEnter() {
								var e = window.event;
								if (e.keyCode == "13") {		
										var myCriteria = $.trim($("#criteria").val());
										loadData(myCriteria);
								}
						}

            window.markerList = markerList;

            markerList.on('selectedChanged', function(event, info) {

                checkBtnStats();

                if (info.selected) {

                    console.log(info);

                    if (info.selected.marker) {
                        //更新为选中样式
                        info.selected.marker.setIconStyle(selectedIconStyle);
                    }

                    //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
                    if (!info.sourceEventInfo.isListElementEvent) {

                        if (info.selected.listElement) {
                            scrollListElementIntoView($(info.selected.listElement));
                        }
                    }
                }

                if (info.unSelected && info.unSelected.marker) {
                    //更新为默认样式
                    info.unSelected.marker.setIconStyle(defaultIconStyle);
                }
            });

            markerList.on('listElementMouseenter markerMouseover', function(event, record) {

                if (record && record.marker) {

                    forcusMarker(record.marker);

                    //this.openInfoWindowOnRecord(record);

                    //非选中的id
                    if (!this.isSelectedDataId(record.id)) {
                        //设置为hover样式
                        record.marker.setIconStyle(hoverIconStyle);
                        //this.closeInfoWindow();
                    }
                }
            });

            markerList.on('listElementMouseleave markerMouseout', function(event, record) {

                if (record && record.marker) {

                    if (!this.isSelectedDataId(record.id)) {
                        //恢复默认样式
                        record.marker.setIconStyle(defaultIconStyle);
                    }
                }
            });

            //数据输出完成
            markerList.on('renderComplete', function(event, records) {

                checkBtnStats();
            });

            //加载数据
            function loadData(criteria) {
            		var newData = filter(criteria);
                markerList.render(newData);
                $("#kount").text(newData.length + "人");
//                map.setFitView();
            }
            
            $("#cities").change(cityChange);
						initCities();
						
						function initCities() {
								var selObj = $("#cities");
								selObj.append("<option>" + "全部" + "</option>");
								var names = [];
								for (var i = 0; i < matesData.length; i += 1) {
										var item = matesData[i];
										var name = item.city;
										if($.inArray(name,names) == -1) {
												names.push(name);
												selObj.append("<option>" + name + "</option>");
										}
								}
						}
            
            function cityChange() {
								var text = $(this).children('option:selected').text();
								var index = $(this).children('option:selected').index();
								if(index == 0) {
										loadData();
								} else {
										var myCriteria = text;
										loadData(myCriteria);
								}
								
						}
            
            function filter(criteria) {
				    		if (criteria == undefined) {
				    				console.log("criteria: " + criteria);
				    				return matesData;
				    		}
				    		var godaddy = [];
				    		console.log("criteria:" + criteria)
								for (var i = 0; i < matesData.length; i++) {
										var item = matesData[i];
								    if (isMatched(item.name, criteria)||isMatched(item.phone, criteria)||isMatched(item.address, criteria)||isMatched(item.city, criteria)) {
								        godaddy.push(item);
								    }
								}
								
								return godaddy;
				    }
				    
				    function isMatched(str, criteria) {
				    		return str.indexOf(criteria) != -1	
				    }

            var $btns = $('#btnList input[data-path]');

            /**
             * 检测各个button的状态
             */
            function checkBtnStats() {
                $('#btnList input[data-enable]').each(function() {

                    var $input = $(this),
                        codeEval = $input.attr('data-enable');

                    $input.prop({
                        disabled: !eval(codeEval)
                    });
                });
            }

            $('#btnList').on('click', 'input', function() {

                var $input = $(this),
                    dataPath = $input.attr('data-path'),
                    codeEval = $input.attr('data-eval');

                if (codeEval) {
                    eval(codeEval);
                }

                checkBtnStats();
            });

            loadData();

            function forcusMarker(marker) {
                marker.setTop(true);

                //不在地图视野内
                if (!(map.getBounds().contains(marker.getPosition()))) {

                    //移动到中心
                    map.setCenter(marker.getPosition());
                }
            }

            function isElementInViewport(el) {
                var rect = el.getBoundingClientRect();

                return (
                    rect.top >= 0 &&
                    rect.left >= 0 &&
                    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                    rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                );
            }

            function scrollListElementIntoView($listEle) {

                if (!isElementInViewport($listEle.get(0))) {
                    $('#panel').scrollTop($listEle.offset().top - $listEle.parent().offset().top);
                }

                //闪动一下
                $listEle
                    .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
                        function(e) {
                            $(this).removeClass('flash animated');
                        }).addClass('flash animated');
            }
        });
       
}